﻿using System;
using System.ComponentModel;
using System.Reflection;
using System.Web.Services;
using CosyTrade.Core;

namespace CosyTrade.Network.WebServicesPortal
{
    /// <summary>
    /// Portal 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    public class Portal : System.Web.Services.WebService
    {
        [WebMethod]
        public byte[] MethodInvoke(byte[] requestData)
        {
            AddinServices service = (AddinServices)Application["AddinServices"];
            if (service == null)
                throw new RemotingException(new NullReferenceException("Application[\"AddinServices\"] Is Null"));

            Request request = (Request)FormatterHelper.BytesToOBject(requestData);
            Response response;
            try
            {
                object reVal = Invoke(service, request.AddinKey, request.ArgsTypes, request.MethodName, request.Args);
                response = new Response(reVal, null);
            }
            catch (Exception ex)
            {
                response = new Response(null, new RemotingException(ex));
            }
            return FormatterHelper.ObjectToBytes(response);

        }

        private static object Invoke(AddinServices service, string addinName, Type[] paramTypes, string methodName, params object[] arguments)
        {
            IAddin targetAddin = service.AddinManager.GetAddin(addinName);
            BindingFlags FindFlags = BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
            MethodInfo invokeMethod = targetAddin.GetType().GetMethod(methodName, FindFlags, null, paramTypes, null);
            return invokeMethod.Invoke(targetAddin, arguments);
        }
    }
}
